package cn.itsource.pet.service.impl;

import cn.itsource.pet.domain.PetType;
import cn.itsource.pet.mapper.PetTypeMapper;
import cn.itsource.pet.service.IPetTypeService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;
    @Override
    public List<PetType> getTypeTree() {
        List<PetType> types = petTypeMapper.findAll();
        ArrayList<PetType> result = new ArrayList<>();
        Map<Long, PetType> collect = types.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
        for (PetType type : types) {
            if(type.getParentId()==null){
                result.add(type);
            }else{
                PetType parent = collect.get(type.getParentId());
                if(parent!=null){
                    parent.getChildren().add(type);
                }
            }
        }
        return result;
    }
}
